﻿using System;
using System.IO;
using System.Xml;
using System.Text;
using System.ServiceModel.Syndication;

namespace NCMIS.ServiceModel.Syndication
{
    public static class SyndicationItemExtensions
    {
        /// <summary>
        /// Write the XML request to a byte array.
        /// </summary>
        /// <param name="entry"></param>
        /// <returns></returns>
        public static byte[] ToByteArray(this SyndicationItem entry)
        {
            StringBuilder builder = new StringBuilder();
            SyndicationItemFormatter formatter = new Atom10ItemFormatter(entry);
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = "\t";
            settings.OmitXmlDeclaration = true;
            using (XmlWriter writer = XmlWriter.Create(builder, settings))
            {
                formatter.WriteTo(writer);
            }
            byte[] bytes = ASCIIEncoding.ASCII.GetBytes(builder.ToString());
            return bytes;
        }

        public static void WriteTo(this SyndicationItem entry, Stream output)
        {
            SyndicationItemFormatter formatter = new Atom10ItemFormatter(entry);
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = "\t";
            settings.OmitXmlDeclaration = true;
            settings.Encoding = Encoding.ASCII;

            using(XmlWriter writer = XmlWriter.Create(output, settings))
            {
                formatter.WriteTo(writer);
                writer.Flush();
                writer.Close();
            }
        }

        // Get binary byte array, include "System.Runtime.Serialization.Formatters.Binary" in using clauses
        //private static byte[] GetBytes(string objectGraph)
        //{
        //    byte[] bytes = null;
        //    try
        //    {
        //        MemoryStream memoryStream = new MemoryStream();
        //        BinaryFormatter binaryFormatter = new BinaryFormatter();
        //        binaryFormatter.Serialize(memoryStream, objectGraph);
        //        bytes = memoryStream.GetBuffer();
        //    }
        //    catch (Exception ex)
        //    {
        //        System.Diagnostics.Debug.WriteLine(ex.Message);
        //    }
        //    return bytes;
        //}
    }
}
